#include <QCoreApplication>

#include <time.h>
#include <QTimer>
#include <QObject>
#include <QFileInfo>
#include <QDir>
#include <QDirIterator>
#include <QProcess>
#include <QDebug>
#include <QThread>
#include <atomic>
#include <QByteArray>
#include <QSettings>
#include <QTextCodec>
#include <QFileSystemWatcher>

#include <singleapplication.h>
#include "assitant.h"


// 随机比应壁纸
const std::string byPic = "https://uploadbeta.com/api/pictures/random/?key=BingEverydayWallpaperPicture";

// 随机美女
const std::string girlPic = "https://uploadbeta.com/api/pictures/random/?key=%E6%8E%A8%E5%A5%B3%E9%83%8E";

//递归遍历文件夹
QFileInfoList GetFileList(QString path)
{
    QDir dir(path);
    QStringList filters;
    filters<<QString("*.jpeg")<<QString("*.jpg")<<QString("*.png")<<QString("*.tiff")
          <<QString("*.gif")<<QString("*.bmp");

    if(dir.isEmpty() || (!dir.exists())){
        qDebug()<<"当前路径图像为空或者路径非法!";
    }

    //列出dir(path)目录文件下所有文件和目录信息，存储到file_list容器
    QFileInfoList file_list = dir.entryInfoList(filters,QDir::Files | QDir::NoSymLinks);
    //列出dir(path)目录下所有子文件夹
    QFileInfoList folder_list = dir.entryInfoList(QDir::Dirs | QDir::NoDotAndDotDot);
    //进行子文件夹folder_list递归遍历，将内容存入file_list容器
    for(int i= 0; i != folder_list.size(); i++)
    {
        QString name = folder_list.at(i).absoluteFilePath();
        QFileInfoList child_file_list = GetFileList(name);
        file_list.append(child_file_list);
    }
    return file_list;
}

int main(int argc, char *argv[])
{
    SingleApplication app(argc, argv);
    if( app.isSecondary() ) {
        QString g = app.arguments().join(' ').toUtf8();
        QByteArray f = QByteArray::fromStdString(g.toStdString());
        app.sendMessage( f );
        qDebug()<<"已有程序运行，本次运行即将关闭";
        app.exit( 0 );
    }

    //Assitant::getHH();
    auto ret = Assitant::getPicTureXmlAndUrl();
    // Assitant::getNewPic(ret,"trmskg.jpg");
    Assitant::getNewPic(ret,"");

//    std::thread([&](){
//        auto ret = Assitant::getPicTureXmlAndUrl();
//        std::cout << ret <<"\n";
//        Assitant::getNewPic(ret,"trmskg.jpg");
//    }).join();


    std::atomic<bool> updatingDirs = ATOMIC_FLAG_INIT;
    QTimer * timer = new QTimer;
    bool transe= false;
    QSettings *configIni = new QSettings("conf.ini", QSettings::IniFormat);
    configIni->setIniCodec(QTextCodec::codecForName("UTF-8")); //在此添加设置，即可读写ini文件中的中文

    QString path=configIni->value(   "paths/path"   ).toString() + "/";
    int count=configIni->value(   "paths/sleep"   ).toInt(&transe);     // 默认时间单位为秒
    if(!transe){
        qDebug()<<"休眠间隔转换失败";
        qDebug()<<"使用默认的时间:30s";
        count = 30;
    }
    qDebug()<<"------------------->"<<path;

    timer->start(count*1000);
    QStringList file_list;
    QFileSystemWatcher *m_fileSystemWatcher = new QFileSystemWatcher;

    auto result = m_fileSystemWatcher->addPath(path);
    if(result){
        QObject::connect(m_fileSystemWatcher,&QFileSystemWatcher::directoryChanged,[&updatingDirs,&file_list](const QString &_path){
            updatingDirs.store(true);
            auto list = GetFileList(_path);
            file_list.clear();
            foreach (auto var, list) {
                file_list.push_back(var.fileName());
            }
            qDebug()<<"已经重新更新了当前文件!";
            updatingDirs.store(false);

        });
    }



    auto list = GetFileList(path);
    foreach (auto var, list) {
        file_list.push_back(var.fileName());
    }


    QObject::connect(timer,&QTimer::timeout,[&updatingDirs,&file_list,&path](){
        static int index = 0;

        if(index >= file_list.count()){
            index = 0;
        }

        if(updatingDirs.load()){
            index = 0;
        }else {
            QString file = "file:"+ path + file_list.at(index);
            QProcess::execute("gsettings set org.gnome.desktop.background picture-uri " + file);    // ubuntu更新壁纸的
            index++;
        }

    });


    return app.exec();
}
